<script setup lang="tsx">
import { } from '@/hooks/common/table';
import { $t } from '@/locales';
import RoleOperateModal from './modules/role-operate-modal.vue';
import RoleSearch from './modules/role-search.vue';
import { fetchTableQuery, useNetoTable, useTableOperate, useTableScroll } from '@/hooks/common/neto-table';
import { ApiRoleOut, ApiRoleQuery, ApiStateInput } from '@/api-services';
import { ApiroleserviceApi } from '@/api-services/apis/apiroleservice-api';
import { feature, getAPI } from '@/axios-utils';
import { ref } from 'vue';
import { queryDone } from '@/utils/api';
import { ElSwitch, ElButton, ElPopconfirm } from 'element-plus';

const { tableWrapperRef, scrollConfig } = useTableScroll();
// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const apiFunc = (params: ApiRoleQuery) => fetchTableQuery<ApiRoleQuery, ApiRoleOut>(
  params,
  (params: ApiRoleQuery) => getAPI(ApiroleserviceApi).getPagedList(params)
);

const loadingStates = ref<Record<string, boolean>>({});
const {
  columns,
  columnChecks,
  data,
  tableSize,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useNetoTable({
  apiFn: apiFunc,
  size: 'small',
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    keyWords: undefined,
    isEnable: undefined,
    startTime: undefined,
    endTime: undefined
  },
  columns: () => [
    { type: 'selection', width: 48 },
    {
      prop: 'id',
      //dataIndex: 'id',
      label: 'Id',
      align: 'center',
      minWidth: 140
    },
    {
      prop: 'name',
      //dataIndex: 'name',
      label: $t('page.manage.role.roleName'),
      align: 'center',
      minWidth: 120
    },
    {
      prop: 'code',
      //dataIndex: 'code',
      label: $t('page.manage.role.roleCode'),
      align: 'center',
      minWidth: 120
    },
    {
      prop: 'isEnable',
      //dataIndex: 'isEnable',
      label: $t('page.manage.role.roleStatus'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.isEnable === null) {
          return '';
        }


        const handleSwitchChange = async (checked: boolean | string | number) => {

          const model: ApiStateInput = {
            id: record.id!,
            state: !!checked,
            field: 'IsEnable'
          }
          //提交请求
          console.log(loading)
          loadingStates.value = {
            ...loadingStates.value,
            [record.id!]: true
          };
          const [err, res] = await feature(getAPI(ApiroleserviceApi).setState(model));
          loadingStates.value = {
            ...loadingStates.value,
            [record.id!]: false
          };
          queryDone(err, async () => {
            if (res?.data.data) {
              record.isEnable = !!checked;
              window.$message?.success($t('common.success'));
            } else {
              window.$message?.error($t('common.failed'));
            }
          })
        }
        return <ElSwitch modelValue={record.isEnable} onChange={handleSwitchChange} loading={loadingStates.value[record.id!] || false}></ElSwitch>
      }
    },
    {
      prop: 'sort',
      //dataIndex: 'sort',
      label: $t('page.manage.role.sort'),
      align: 'center',
      minWidth: 120

    },
    {
      prop: 'remark',
      //dataIndex: 'remark',
      label: $t('page.manage.role.roleDesc'),
      align: 'center',
      minWidth: 100
    },
    {
      //创建时间
      prop: 'creationTime',
      //dataIndex: 'creationTime',
      label: $t('common.creationTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //创建人
      prop: 'creatorUserName',
      //dataIndex: 'creatorUserName',
      label: $t('common.creatorUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      //修改时间
      prop: 'updateTime',
      //dataIndex: 'updateTime',
      label: $t('common.updateTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //修改人
      prop: 'updateUserName',
      //dataIndex: 'updateUserName',
      label: $t('common.updateUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      prop: 'index',
      label: $t('common.operate'),
      align: 'center',
      minWidth: 230,
      fixed: 'right',
      formatter: record => (
        <div class="flex-center gap-8px">
          <ElButton type="primary" plain size="small" onClick={() => edit(record.id!)}>
            {$t('common.edit')}
          </ElButton>
          <ElPopconfirm onConfirm={() => handleDelete(record.id!)} title={$t('common.confirmDelete')}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});
const {
  isVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  //rowSelection,
  onBatchDeleted,
  onDeleted

} = useTableOperate(data, getData);

async function handleBatchDelete() {
  // request

  onBatchDeleted();
}

function handleDelete(id: number) {
  // request
  console.log(id);

  onDeleted();
}

function edit(id: number) {
  handleEdit(id);
}

</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <RoleSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.manage.role.title') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            :loading="loading" @add="handleAdd" @delete="handleBatchDelete" @refresh="getData" />
        </div>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>
      <RoleOperateModal v-model:visible="isVisible" :operate-type="operateType" :row-data="editingData"
        @submitted="getDataByPage" />
    </ElCard>
  </div>
</template>

<style scoped></style>
